package cn.ekuma.epos.datalogic.businesslogic;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.xeoh.plugins.base.PluginManager;
import net.xeoh.plugins.base.util.PluginManagerUtil;
import com.openbravo.bean.erp.Order;
import com.openbravo.data.basic.BasicException;

import cn.ekuma.epos.datalogic.I_DataLogicERP;
import cn.ekuma.epos.datalogic.businesslogic.orderrule.I_OrderRule;
import cn.ekuma.epos.datalogic.businesslogic.orderrule.I_OrderRuleManager;
import cn.ekuma.epos.datalogic.businesslogic.orderrule.RuleMessage;

public class OrderRuleManager implements I_OrderRuleManager{

	private Map<String,I_OrderRule> processMap=new HashMap<String,I_OrderRule>();
	private Map<String,List<String>> orderTypeRuleSuperedMap=new HashMap<String,List<String>>();
	
	
	@Override
	public List<RuleMessage> isPass(I_DataLogicERP dlERP, Order order) throws BasicException{
		List<RuleMessage> retMessage=new ArrayList<RuleMessage>();
		List<RuleMessage> subretMessage=null;
		String orderTypeId=order.getDefineType().getId();
		for(I_OrderRule orderProcess:processMap.values()){
			if(!getOrderSuperedRule(dlERP,orderTypeId).contains(orderProcess.getName()))
				continue;
			HashMap prop=getOrderRuleProp( dlERP, order.getDefineType().getId(), orderProcess.getName());
			subretMessage=orderProcess.isPass(dlERP, order, prop);
			if(subretMessage!=null)
				retMessage.addAll(subretMessage);
		}
		return retMessage.isEmpty()?null:retMessage;
	}

	@Override
	public HashMap getOrderRuleProp(I_DataLogicERP dlERP, String orderTypeId,String ruleName) throws BasicException {
		I_OrderRule orderProcess=processMap.get(ruleName);
		if(orderProcess==null)
			throw new BasicException("no found orderRule in local plugins:"+ruleName);
		HashMap ret=dlERP.findOrderRulePropByNameAndOrderType(orderTypeId,ruleName);	
		if(ret==null)
			ret=orderProcess.getConfigProp();
		return ret;
	}

	public List<String> getOrderSuperedRule(I_DataLogicERP dlERP,String orderTypeId)throws BasicException {
		List<String> ret=orderTypeRuleSuperedMap.get(orderTypeId);
		if(ret==null){
			ret=dlERP.findOrderSuperedRuleByOrderType(orderTypeId);
			if(ret==null)
				ret=new ArrayList();
			orderTypeRuleSuperedMap.put(orderTypeId, ret);
		}	
		return ret;
	}
	
	@Override
	public void init(PluginManager pmf) { 
		PluginManagerUtil pmu = new PluginManagerUtil(pmf);
    	Collection<I_OrderRule> plugins1 = pmu.getPlugins(I_OrderRule.class);
    	for(I_OrderRule orderProcess:plugins1){
    		processMap.put(orderProcess.getName(), orderProcess);
    	}
	}
	
	public List<String> getAllOrderRule()throws BasicException {
		List<String> ret=new ArrayList();
		for(String ruleName:processMap.keySet())
			ret.add(ruleName);	
		return ret;
	}
}
